﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI;

public partial class View_ManageUsers : System.Web.UI.Page
{
    private ManageUsers mgUsers;
    private string SESSION_SEARCH = "SEARCH";

    protected void Page_Load(object sender, EventArgs e)
    {
        mgUsers = new ManageUsers();
        try
        {
            string season = Session["Login"].ToString();
            if (season != null)
            {
                if (season.Contains("user"))
                {
                    HttpApplication httpApp = HttpContext.Current.ApplicationInstance;

                    httpApp.Response.Redirect("~/Default.aspx");
                }
            }
            else
            {
                HttpApplication httpApp = HttpContext.Current.ApplicationInstance;

                httpApp.Response.Redirect("~/Login.aspx");
            }
        }
        catch (Exception ex)
        {
            HttpApplication httpApp = HttpContext.Current.ApplicationInstance;

            httpApp.Response.Redirect("~/Login.aspx");
        }
        if (!IsPostBack)
        {
            Session.Remove(SESSION_SEARCH);
        }
        ScriptManager.GetCurrent(Page).RegisterPostBackControl(tbnExport);
    }

    protected void tbnExport_Click(object sender, EventArgs e)
    {
        rdgUsers.ExportSettings.Excel.Format = (GridExcelExportFormat)Enum.Parse(typeof(GridExcelExportFormat), "ExcelML");
        rdgUsers.ExportSettings.IgnorePaging = true;
        rdgUsers.ExportSettings.ExportOnlyData = true;
        rdgUsers.ExportSettings.OpenInNewWindow = true;
        rdgUsers.ExportSettings.FileName = "Danh-sach-nhan-vien-" + DateTime.Now.ToString();
        rdgUsers.MasterTableView.ExportToExcel();
    }
    /// <summary>
    /// Su kien click tren button search
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string stringSearch = txtKeyWord.Text.Trim();
        if (txtKeyWord.Text.Trim() == String.Empty)
        {
            stringSearch = hdfSearchString.Value.Trim();
        }

        if (Session[SESSION_SEARCH] != null)
        {
            if (hdfSearchString.Value.Trim() != Session[SESSION_SEARCH].ToString())
            {
                stringSearch = hdfSearchString.Value.Trim();
            }
            if (Session[SESSION_SEARCH].ToString() != txtKeyWord.Text.Trim())
            {
                stringSearch = txtKeyWord.Text.Trim();
            }
        }

        hdfSearchString.Value = stringSearch;
        rdgUsers.DataSource = mgUsers.searchUsersByKeyword(stringSearch);
        rdgUsers.Rebind();
        Session[SESSION_SEARCH] = stringSearch;
        txtKeyWord.Text = stringSearch;
    }

    /// <summary>
    /// Ham day du lieu vao radGrid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgUsers_NeedDataSource(object sender, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        if ((Session[SESSION_SEARCH] != null) && (Session[SESSION_SEARCH].ToString() != string.Empty))
        {
            rdgUsers.DataSource = mgUsers.searchUsersByKeyword(Session[SESSION_SEARCH].ToString());
        }
        else
        {
            rdgUsers.DataSource = mgUsers.getAllUsers();
        }
    }

    /// <summary>
    /// Ham insert du lieu vao radGrid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgUsers_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        GridEditableItem editedItem = e.Item as GridEditableItem;
        Users user = new Users();
        TextBox txtUserName = editedItem.FindControl("txtUserName") as TextBox;
        TextBox txtPass = editedItem.FindControl("txtPass") as TextBox;
        RadDatePicker DateOfBirth = editedItem.FindControl("BirthDatePicker") as RadDatePicker;
        TextBox txtPhone = editedItem.FindControl("txtPhone") as TextBox;
        TextBox txtEmail = editedItem.FindControl("txtEmail") as TextBox;
        user.UserName = txtUserName.Text;
        user.Pass = txtPass.Text;
        DateTime temp;
        DateTime.TryParse(DateOfBirth.SelectedDate.ToString(), out temp);
        user.DateOfBirth = temp;
        user.Phone = txtPhone.Text;
        user.Email = txtEmail.Text;

        int _result = mgUsers.insertNeuUser(user);
        if (_result > 1)
            Message.Show(rapUsers, "Thêm dữ liệu thành công!", Message.Type.Success);
        else if (_result == 0)
            Message.Show(rapUsers, "Tài khoản đã tồn tại", Message.Type.Error);
        else
            Message.Show(rapUsers, "Thêm không thành công : Lỗi hệ thống", Message.Type.Error);
        rdgUsers.CurrentPageIndex = 0;
    }

    /// <summary>
    /// Ham delete 1 hang cua radgrid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgUsers_DeleteCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
    {
        int pageIndex = rdgUsers.CurrentPageIndex;
        GridEditableItem editedItem = e.Item as GridEditableItem;

        Users user = new Users();

        int userId;
        user.IDUser = int.TryParse(editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex][UsersColumn.IDUser].ToString(), out userId) ? userId : 0;

        int _result = mgUsers.deleteUser(user);
        if (_result == 1)
            Message.Show(rapUsers, "Xóa dữ liệu thành công!", Message.Type.Success);
        else if (_result == 0)
            Message.Show(rapUsers, "Xóa dữ liệu không thành công", Message.Type.Error);
        else
            Message.Show(rapUsers, "Xóa không thành công : Lỗi hệ thống", Message.Type.Error);
        rdgUsers.CurrentPageIndex = pageIndex;
    }

    /// <summary>
    /// Kiem tra check luc day du lieu vao radGrid
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void rdgUsers_ItemDataBound(object sender, GridItemEventArgs e)
    {
        if (e.Item is GridDataItem)
        {
            GridDataItem item = e.Item as GridDataItem;
            Label lblDateOfBirth = (Label)item.FindControl("lblDateOfBirth");
            DateTime temp;
            DateTime.TryParse(lblDateOfBirth.Text, out temp);
            lblDateOfBirth.Text = String.Format("{0:dd/MM/yyyy}", temp);
           
            ImageButton Edit = ((ImageButton)item["Edit"].Controls[0]);
            Edit.CssClass = "btnEditDelete";
            Edit.Width = 20;
            Edit.Height = 20;
            Edit.Attributes.Add("style", "background-color:transparent");
            ImageButton Delete = ((ImageButton)item["Delete"].Controls[0]);
            Delete.CssClass = "btnEditDelete";
            Delete.Width = 20;
            Delete.Height = 20;
            Delete.Attributes.Add("style", "background-color:transparent;");
        }
        if (e.Item.IsInEditMode)
        {
            GridEditFormItem item = e.Item as GridEditFormItem;
            Button btnAdd = new Button();
            btnAdd = item.FindControl("PerformInsertButton") as Button;
            if (e.Item is GridEditFormInsertItem || e.Item is GridDataInsertItem)
            {
                btnAdd.Text = "Thêm mới";
                btnAdd.CssClass = "myButton";
            }
            else
            {
                Button btnUpdate = new Button();
                btnUpdate = item.FindControl("UpdateButton") as Button;
                btnUpdate.Text = "Chỉnh sửa";
                btnUpdate.CssClass = "myButton";
            }
            Button btnCancel = new Button();
            btnCancel = item.FindControl("CancelButton") as Button;
            btnCancel.Text = "Hủy bỏ";
            btnCancel.CssClass = "myButton";
        }
    }

    protected void rdgUsers_UpdateCommand(object sender, GridCommandEventArgs e)
    {
        int pageIndex = rdgUsers.CurrentPageIndex;
        GridEditableItem editedItem = e.Item as GridEditableItem;
        
        Users user = new Users();

        int userId;
        user.IDUser = int.TryParse(editedItem.OwnerTableView.DataKeyValues[e.Item.ItemIndex][UsersColumn.IDUser].ToString(), out userId) ? userId : 0;
        TextBox txtUserName = editedItem.FindControl("txtUserName") as TextBox;
        TextBox txtPass = editedItem.FindControl("txtPass") as TextBox;
        RadDatePicker DateOfBirth = editedItem.FindControl("BirthDatePicker") as RadDatePicker;
        TextBox txtPhone = editedItem.FindControl("txtPhone") as TextBox;
        TextBox txtEmail = editedItem.FindControl("txtEmail") as TextBox;
        user.UserName = txtUserName.Text;
        user.Pass = txtPass.Text;
        DateTime temp;
        DateTime.TryParse(DateOfBirth.SelectedDate.ToString(), out temp);
        user.DateOfBirth = temp;
        user.Phone = txtPhone.Text;
        user.Email = txtEmail.Text;

        int _result = mgUsers.updateUser(user);
       
        if (_result == 1)
            Message.Show(rapUsers, "Chỉnh sửa dữ liệu thành công!", Message.Type.Success);
        else if (_result == 0)
            Message.Show(rapUsers, "Chỉnh sửa dữ liệu không thành công:Vui lòng chọn tên khác !", Message.Type.Error);
        else
            Message.Show(rapUsers, "Chỉnh sửa dữ liệu không thành công : Lỗi hệ thống", Message.Type.Error);
        rdgUsers.CurrentPageIndex = pageIndex;
    }

}